package com.weipai.education.service.impl;

import com.weipai.education.service.WeChatService;
import com.weipai.education.utils.PropUtils;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: 曹朋飞
 * @Date: 2018/12/25 20:15
 */
@Service
public class WeChatServiceImpl implements WeChatService {
    
    private static final Logger logger = LoggerFactory.getLogger(WeChatServiceImpl.class);

    //获取code回调地址
    private static String call_back_url = PropUtils.getString("call_back_url");

    @Autowired
    private WxMpService wxMpService;

    @Override
    public String oauth2buildAuthorizationUrl(String returnUrl) {
        String oauthUrl = wxMpService.oauth2buildAuthorizationUrl(call_back_url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        return "redirect:" + oauthUrl;
    }

    @Override
    public String callBackUrl(String code, String returnUrl) {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            logger.error("callBackUrl error {}", e);
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        return "redirect:" + returnUrl + "?openid=" + openId;
    }

    @Override
    public String getUserByOpenId(String openId) {
        return null;
    }

    private String send(String openId){
        //实例化模板对象
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        //设置模板ID
        wxMpTemplateMessage.setTemplateId("");
        //设置发送给哪个用户
        wxMpTemplateMessage.setToUser(openId);
        //构建消息格式
        List<WxMpTemplateData> list= Arrays.asList(
                new WxMpTemplateData("first","wen"),
                new WxMpTemplateData("keyword1","wen"),
                new WxMpTemplateData("keyword2","wen"),
                new WxMpTemplateData("keyword3","wen"),
                new WxMpTemplateData("keyword4","wen"),
                new WxMpTemplateData("remark","wen")
        );
        //放进模板对象。准备发送
        wxMpTemplateMessage.setData(list);
        try {
            //发送模板
            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "发送成功";
    }
    
    
    
    
    

    /*@GetMapping
    public String check(String signature, String timestamp, String nonce, String echostr) {
        if (iService.checkSignature(signature, timestamp, nonce, echostr)) {
            return echostr;
        }
        return null;
    }

    @PostMapping
    public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        try {
            // 微信服务器推送过来的是XML格式。
            WxXmlMessage wx = XStreamTransformer.fromXml(WxXmlMessage.class, request.getInputStream());
            System.out.println("消息：\n " + wx.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }

    }

    *//**
     * 根据openId获取用户信息
     * @param openId
     *//*
    @GetMapping
    public void getUserInfoByOpenId(String openId){
        try {
            WxUserList.WxUser user = iService.getUserInfoByOpenId(new WxUserList.WxUser.WxUserGet(openId, WxConsts.LANG_CHINA));
            System.out.println(user.toString());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }






    *//**
     * 发送消息模板
     * @param openId
     *//*
    @GetMapping
    public void templateSend(String openId){
        TemplateSender sender = new TemplateSender();
        sender.setTouser(openId);
        sender.setTemplate_id("templateId");
        sender.setData("Object：与模板内容对应的对象");
        sender.setUrl("url");
        try {
            TemplateSenderResult result = iService.templateSend(sender);
            System.out.println(result.toString());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }*/
    
    
}
